/*
** main.c for Main in /home/vriely/Work/Unix/Tp_Ftp
**
** Made by Samuel Vrielynck
** Login   <@epitech.net>
**
** Started on  Mon Apr 02 16:01:20 2012 Samuel Vrielynck
** Last update Thu Jul 19 17:51:50 2012 pierrick druart
*/

#include		<stdio.h>
#include		<stdlib.h>
#include		<string.h>

#include		"server.h"

static t_pars		ptr_pars[]=
  {
    {"-n", &add_team},
    {"-x", &init_x},
    {"-y", &init_y},
    {"-t", &init_time},
    {"-p", &init_port},
    {"-c", &init_client},
    {NULL, 0}
  };

static void		set_team_number(void *content, void *nb_player_ptr)
{
  struct s_team		*team;

  team = (struct s_team *) content;
  team->slot = *(int *) nb_player_ptr;
}

int			add_team(const char *argv[], unsigned int *i, t_game *game)
{
  t_list		*team;

  team = game->team;
  if (strncmp("-", argv[*i + 1], 1))
    {
      (*i)++;
      while (argv[*i] != NULL && strncmp("-", argv[*i], 1) != 0)
	{
	  team->add_back(team, new_team(argv[*i]));
	  (*i)++;
	}
      (*i)--;
      return (0x00100000);
    }
  fprintf(stderr, "Usage: add client error.\n");
  return (0);
}

static int		parser(t_game *game, const char *argv[])
{
  unsigned int		i;
  int			j;
  int			bit;

  i = 1;
  bit = 0;
  while (argv[i])
    {
      j = 0;
      while (ptr_pars[j].cmd)
	{
	  if (!strcmp(argv[i], ptr_pars[j].cmd))
	    {
	    if (!argv[i + 1])
	      return (0);
	    bit |= ptr_pars[j].cmdfct(argv, &i, game);
	    }
	  j++;
	}
      i++;
    }
  return (bit);
}

int			main(int argc, const char *argv[])
{
  t_game		*game;

  (void) argc;
  game = new_game();
  if (parser(game, argv) == BIT)
  {
    if ((game->serverfd = init(game->port_index)) != -1 && game->nb_player > 0)
    {
      init_game(game);
      game->team->foreach(game->team, &set_team_number, &(game->nb_player));
      exec(game);
      xclose(game->serverfd);
      free_obj(game);
    }
    else
      fprintf(stderr, "Error in server connection.\n");
  }
  else
    fprintf(stderr, "Usage: ./zappy-serv\n\t-p <port>\n\t-x <width> \
	\n\t-y <height>\n\t-n <team name> \
       \n\t-c <client at beginning of game>\n\t-t [time]\n");
  delete_game(game);
  return (EXIT_SUCCESS);
}

